package utils

import (
	"go-ecommerce/config"
	"io"
	"os"
	"time"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

var Logger zerolog.Logger

func InitLogger() {
	// 控制台格式化输出
	consoleWriter := zerolog.ConsoleWriter{
		Out:        os.Stdout,
		TimeFormat: time.RFC3339,
	}

	// 定义通用 io.Writer 类型的 writer
	var writer io.Writer = consoleWriter

	// 如果设置了日志文件
	if config.Conf.Log.Filename != "" {
		logFile, err := os.OpenFile(config.Conf.Log.Filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
		if err != nil {
			log.Fatal().Err(err).Msg("打开日志文件失败")
		}
		// 合并控制台和文件输出（这里 MultiLevelWriter 参数类型是 io.Writer，不是 LevelWriter）
		writer = zerolog.MultiLevelWriter(consoleWriter, logFile)
	}

	// 设置日志级别
	level, err := zerolog.ParseLevel(config.Conf.Log.Level)
	if err != nil {
		level = zerolog.InfoLevel
	}

	// 创建全局 logger
	Logger = zerolog.New(writer).With().Timestamp().Logger().Level(level)

	// 设置全局默认 logger
	zerolog.DefaultContextLogger = &Logger
}
